package com.y.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * �����ҿͻ���
 * @author Administrator
 *
 */
public class Client {
	/**
	 * java.net.Socket
	 * ��װ��TCPЭ�飬ʹ�����Ϳ��Ի���TCPЭ��
	 * ��������ͨѶ
	 * Socket�������ڿͻ��˵�
	 */
	private Socket socket;
	
	/**
	 * ���췽����������ʼ���ͻ���
	 * ʵ����Socket��ʱ����Ҫ��������������
	 * 1������˵�ַ��ͨ��Ip��ַ�����ҵ�����˵ļ����
	 * 2������˶˿ڣ�ͨ���˿ڿ����ҵ�����˼�����ϵķ����Ӧ�ó���
	 * ʵ����Socket�Ĺ��̾������ӵĹ��̣���Զ�˼����û����Ӧ���׳��쳣
	 * @throws Exception
	 */
	public Client()throws Exception{
		System.out.println("�������ӷ���ˡ���������");
		socket = new Socket(
					"y949548818.6655.la",18745
				);
		System.out.println("�����˳ɹ��������ӣ�");
	}
	/**
	 * �����ͻ��˵ķ���
	 */
	public void start(){
		Scanner s = new Scanner(System.in);
		String nickName = null;
		while(true){
			System.out.println("�������û��ǳ�,����Ϊ3��");
			 if ((nickName=s.nextLine())!=null) {
				  break;
			}
			 System.out.println("�������");
		}
		System.out.println("��ӭ��"+nickName+"��ʼ����ɣ�");
		
		try {
			/**
			 * Socket�ṩ�ķ�����
			 * OutputStream getOutputStream
			 * ��ȡһ���ֽ��������ͨ������д�������ݻᱻ������Զ�˼����
			 */
			//д��
			OutputStream out = socket.getOutputStream();
			OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
			PrintWriter pw = new PrintWriter(osw,true);
			
			ServerHandler handler= new ServerHandler(socket); 
			Thread t = new Thread(handler);
			t.start();
			
			pw.println(nickName);
			while (true) {
				pw.println(s.nextLine());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		
		try {
			Client client = new Client();
			client.start();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("�ͻ�������ʧ�ܣ�");
		}
	}
	
	class ServerHandler implements Runnable{
		private Socket socket;
		
		public ServerHandler(Socket socket){
			this.socket = socket;
		}
		public void run() {
			try {
				InputStream in = socket.getInputStream();
				InputStreamReader isr = new InputStreamReader(in,"UTF-8");
				BufferedReader br = new BufferedReader(isr);
				String message = null;
				while ((message = br.readLine())!=null) {
					System.out.println(message);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}










